﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace HttpRequestDemo
{
    class HttpRequestHelper
    {
        /// <summary>
        /// 请求超时时间
        /// </summary>
        static readonly int MAX_TIME = 10;

        /// <summary>
        /// 携带Token进行带参数的异步get请求
        /// </summary>
        /// <param name="Url">接口地址</param>
        /// <param name="parameter">入参</param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetWithTokenAsync(string Url, string parameter, string token)
        {
            string result = string.Empty;

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 超时时间
                    client.Timeout = TimeSpan.FromSeconds(MAX_TIME);
                    // Token
                    client.DefaultRequestHeaders.Add("Token", token);
                    // 携带参数异步查询
                    HttpResponseMessage response = await client.GetAsync(Url + parameter).ConfigureAwait(false);
                    // 返回查询结果
                    return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"访问{Url + parameter}出错，{e.Message}");
                return result;
            }
        }

        /// <summary>
        /// 携带Token进行带参数的异步get请求
        /// </summary>
        /// <param name="Url">接口地址</param>
        /// <param name="parameter">入参</param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(string Url, string parameter)
        {
            string result = string.Empty;

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 超时时间
                    client.Timeout = TimeSpan.FromSeconds(MAX_TIME);
                    // 携带参数异步查询
                    HttpResponseMessage response = await client.GetAsync(Url + parameter).ConfigureAwait(false);
                    // 返回查询结果
                    return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"访问{Url + parameter}出错，{e.Message}");
                return result;
            }
        }

        /// <summary>
        /// 携带Token进行无参数的异步get请求
        /// </summary>
        /// <param name="Url">接口地址</param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetWithTokenAsync(string Url, string token)
        {
            string result = string.Empty;

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 超时时间
                    client.Timeout = TimeSpan.FromSeconds(MAX_TIME);
                    // Token
                    client.DefaultRequestHeaders.Add("Token", token);
                    // 携带参数异步查询
                    HttpResponseMessage response = await client.GetAsync(Url).ConfigureAwait(false);
                    // 返回查询结果
                    return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"访问{Url}出错，{e.Message}");
                return result;
            }
        }

        /// <summary>
        /// 无Token无参的异步get请求
        /// </summary>
        /// <param name="Url">接口地址</param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(string Url)
        {
            string result = string.Empty;

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 超时时间
                    client.Timeout = TimeSpan.FromSeconds(MAX_TIME);
                    // 携带参数异步查询
                    HttpResponseMessage response = await client.GetAsync(Url).ConfigureAwait(false);
                    // 返回查询结果
                    return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"访问{Url}出错，{e.Message}");
                return result;
            }
        }

        /// <summary>
        /// 带参数的异步post请求（Json入参）
        /// </summary>
        /// <param name="Url">接口地址</param>
        /// <param name="parameter">入参</param>
        /// <returns></returns>
        public static async Task<string> HttpPostAsync(string Url, string parameter)
        {
            string result = string.Empty;
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 超时时间
                    client.Timeout = TimeSpan.FromSeconds(MAX_TIME);
                    // 携带参数异步查询,如果不设置ContentType，会一直等待
                    using (var content = new StringContent(parameter, Encoding.UTF8, "application/json"))
                    {
                        HttpResponseMessage response = await client.PostAsync(Url, content).ConfigureAwait(false);
                        // 返回查询结果
                        return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"访问{Url + parameter}出错，{e.Message}");
                return result;
            }
        }

        /// <summary>
        /// 带参数的异步post请求（Json入参）
        /// </summary>
        /// <param name="Url">接口地址</param>
        /// <param name="parameter">入参</param>
        /// <returns></returns>
        public static async Task<string> HttpPostAsync(string Url, Dictionary<string, string> dic, string parameter)
        {
            string result = string.Empty;
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 超时时间
                    client.Timeout = TimeSpan.FromSeconds(MAX_TIME);
                    // 携带参数异步查询,如果不设置ContentType，会一直等待
                    using (var content = new MultipartContent())
                    {
                        FormUrlEncodedContent content1 = new FormUrlEncodedContent(dic);
                        content.Add(content1);
                        StringContent contetnt2 = new StringContent(parameter, Encoding.UTF8, "application/json");
                        content.Add(contetnt2);
                        HttpResponseMessage response = await client.PostAsync(Url, content).ConfigureAwait(false);
                        // 返回查询结果
                        return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"访问{Url + parameter}出错，{e.Message}");
                return result;
            }
        }

        /// <summary>
        /// 带参数的异步post请求  表单  query入参(URL入参)
        /// </summary>
        /// <param name="Url">接口地址</param>
        /// <param name="parameter">入参</param>
        /// <returns></returns>
        public static async Task<string> HttpPostQueryAsync(string Url, string parameter)
        {
            string result = string.Empty;
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 超时时间
                    client.Timeout = TimeSpan.FromSeconds(MAX_TIME);
                    // 携带参数异步查询,如果不设置ContentType，会一直等待
                    using (var content = new StringContent(""))
                    {
                        HttpResponseMessage response = await client.PostAsync(Url + parameter, content).ConfigureAwait(false);
                        // 返回查询结果
                        return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"访问{Url}出错，{e.Message}");
                return result;
            }
        }

        /// <summary>
        /// 携带token进行带参数的异步post请求
        /// </summary>
        /// <param name="Url">接口地址</param>
        /// <param name="parameter">入参</param>
        /// <returns></returns>
        public static async Task<string> HttpPostWithTokenAsync(string Url, string parameter, string token)
        {
            string result = string.Empty;
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 超时时间
                    client.Timeout = TimeSpan.FromSeconds(MAX_TIME);
                    // Token
                    client.DefaultRequestHeaders.Add("Token", token);
                    // 携带参数异步查询,如果不设置ContentType，会一直等待
                    using (var content = new StringContent(parameter, Encoding.UTF8, "application/json"))
                    {
                        HttpResponseMessage response = await client.PostAsync(Url, content).ConfigureAwait(false);
                        // 返回查询结果
                        return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"访问{Url + parameter}出错，{e.Message}");
                return result;
            }
        }

        /// <summary>
        /// Post多文件上传
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="dicParameter">表单类型参数</param>
        /// <param name="jsonPara">Json类型参数</param>
        /// <param name="token">token</param>
        /// <returns></returns>
        public static async Task<string> HttpPostWithTokenAsync(string Url, Dictionary<string, FileStream> fileList, string data, string token)
        {
            string result = string.Empty;
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 超时时间
                    //client.Timeout = TimeSpan.FromSeconds(MAX_TIME);
                    // Token
                    client.DefaultRequestHeaders.Add("Token", token);
                    using (var content = new MultipartFormDataContent())
                    {
                        // 循环添加文件
                        foreach (var f in fileList)
                        {
                            // 文件流
                            var dicContent = new StreamContent(f.Value);
                            // 文件流   对应的入参的参数名称  文件流名称
                            content.Add(dicContent, "fileList", $"{f.Key}.png");
                        }
                        // 异步请求
                        HttpResponseMessage response = await client.PostAsync(Url + data, content).ConfigureAwait(false);
                        // 返回查询结果
                        return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"访问{Url}出错，{e.Message}");
                return result;
            }
        }

        /// <summary>
        /// 带参数的异步put请求(键值对和Json同时入参)
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="dicParameter">表单类型参数</param>
        /// <param name="jsonPara">Json类型参数</param>
        /// <returns></returns>
        public static async Task<string> HttpPutAsync(string Url, Dictionary<string, string> dicParameter, string jsonPara)
        {
            string result = string.Empty;
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 超时时间
                    client.Timeout = TimeSpan.FromSeconds(MAX_TIME);
                    using (var content = new MultipartFormDataContent())
                    {
                        // 整合参数
                        var dicContent = new FormUrlEncodedContent(dicParameter);
                        content.Add(dicContent);
                        var jsonContent = new StringContent(jsonPara, Encoding.UTF8, "application/json");
                        content.Add(jsonContent);
                        // 异步请求
                        HttpResponseMessage response = await client.PutAsync(Url, content).ConfigureAwait(false);
                        // 返回查询结果
                        return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"访问{Url}出错，{e.Message}");
                return result;
            }
        }

        /// <summary>
        /// 带参数的异步put请求（Json入参）
        /// </summary>
        /// <param name="Url">接口地址</param>
        /// <param name="parameter">入参</param>
        /// <returns></returns>
        public static async Task<string> HttpPutAsync(string Url, string parameter)
        {
            string result = string.Empty;
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 超时时间
                    client.Timeout = TimeSpan.FromSeconds(MAX_TIME);
                    // 携带参数异步查询,如果不设置ContentType，会一直等待
                    using (var content = new StringContent(parameter, Encoding.UTF8, "application/json"))
                    {
                        HttpResponseMessage response = await client.PutAsync(Url, content).ConfigureAwait(false);
                        // 返回查询结果
                        return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"访问{Url + parameter}出错，{e.Message}");
                return result;
            }
        }

        /// <summary>
        /// 带参数的异步put请求（Json入参）
        /// </summary>
        /// <param name="Url">接口地址</param>
        /// <param name="parameter">入参</param>
        /// <returns></returns>
        public static async Task<string> HttpPutWithTokenAsync(string Url, string parameter, string token)
        {
            string result = string.Empty;
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 超时时间
                    client.Timeout = TimeSpan.FromSeconds(MAX_TIME);
                    // token
                    client.DefaultRequestHeaders.Add("Token", token);
                    // 携带参数异步查询,如果不设置ContentType，会一直等待
                    using (var content = new StringContent(parameter, Encoding.UTF8, "application/json"))
                    {
                        HttpResponseMessage response = await client.PutAsync(Url, content).ConfigureAwait(false);
                        // 返回查询结果
                        return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine($"访问{Url + parameter}出错，{e.Message}");
                return result;
            }
        }
    }
}
